<template>
  <el-dialog :title="data == null ? '添加' : '编辑'" :visible.sync="visible">
    <el-form
      ref="main-form"
      status-icon
      :model="mainQuery"
      :rules="rules"
      label-width="120px"
      label-position="left"
      :inline="false"
      style="width: 400px"
    >
      <!-- <el-form-item label="ID" size="mini" v-if="id != null">
        <el-input placeholder="" onfocus="this.select()" v-model="id" readonly></el-input>
      </el-form-item> -->

      <el-form-item label="标题" size="mini" prop="protocolName">
        <el-input
          placeholder=""
          v-model="mainQuery.protocolName"
          :disabled="loading"
          @keyup.enter.native="submit"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="电子协议" prop="urllist" required>
        <el-upload
          :file-list="mainQuery.urllist"
          action="#"
          :limit="10"
          multiple
          accept=".pdf,.png"
          :on-exceed="
            () => {
              this.$message({ message: '超出最大限制', type: 'warning' });
            }
          "
          :before-upload="BeforeUpload"
          :on-change="handleFileChange"
          :http-request="handleFileUpload"
          :on-success="handleFileUploadsucceed"
        >
          <el-button size="small" type="primary" icon="el-icon-upload"
            >点击上传</el-button
          >
          <div slot="tip" class="el-upload__tip">上传电子协议PDF文件</div>
        </el-upload>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="close" size="mini">取 消</el-button>
      <el-button @click="submit" size="mini" type="primary" :loading="loading"
        >提 交</el-button
      >
    </div>
  </el-dialog>
</template>

<script>

import util from '@/libs/util';
import ApiMain from '@/api/system.agreement';
import ApiRole from '@/api/system.role';
import dayjs from "dayjs";
import { updataFileOss } from '@/api/tools.js'
import CascaderSystemNode from '@/components/system/cascader-system-node';

export default {
  mixins: [
  ],

  components: {
    'cascader-system-node': CascaderSystemNode,
  },
  data() {

    return {

      visible: false,
      popDeleteVisible: false,
      loading: false,

      mainQueryRaw: null,
      mainQuery: {
        protocolName: '',
        urllist: [],
      },

      rules: {
        seveTime: [
          { required: true, message: '请选择展示时间', trigger: 'blur' },
        ],
        protocolName: [
          { required: true, message: '请输入名称', trigger: 'blur' },
        ],
        isTop: [
          { required: true, message: '请选择状态', trigger: 'blur' },
        ],
        type: [
          { required: true, message: '请选择状态', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入富文本内容', trigger: 'blur' },
        ],

      },

      id: null,
      data: null,

    }
  },
  mounted() {
    this.mainQueryRaw = Object.copy(this.mainQuery);
  },

  methods: {
    handleFileUploadsucceed(file, fileList, list) {
      let url = file.requestUrls[0];
      if (url.split('?').length > 1) {
        let index = url.indexOf('?');
        url = url.substr(0, index);
      }
      console.log(file, fileList, list);
      this.mainQuery.urllist = [{
        url: url,
        name: fileList.name
      }];
    },
    BeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 10;
      if (!isRightSize) {
        this.$message.error("文件大小超过 10MB");
      }
      return isRightSize;
    },
    handleFileChange(fileList, list) {

    },
    async handleFileUpload(params, type) {
      console.log(params)
      let data = await updataFileOss(params, type)
      console.log(data);
      return data.res
    },

    async show(data) {
      this.reset();
      this.roleOptions = await ApiRole.getOptions()
      if (data) {
        this.data = data;
        this.fetchData();
      }

      this.visible = true;
    },

    close() {
      this.visible = false;
      this.$emit('dialog-close');
    },

    reset() {
      this.mainQuery = Object.copy(this.mainQueryRaw);
      this.$refs['main-form'] && this.$refs['main-form'].resetFields();
      this.$refs['cascader-system-node'] && this.$refs['cascader-system-node'].fetchOptions();
      this.id = null;
      this.data = null;
    },

    async fetchData() {
      this.loading = true;
      this.data.urllist = [{
        url: this.data.url,
        name: this.data.protocolName + '.pdf'
      }]

      if (this.data) {
        for (var k in this.mainQuery) {
          this.mainQuery[k] = this.data[k];
        }
      }
      console.log(this.mainQuery);

      this.loading = false;
    },

    verifyForm() {
      var bool = true;
      this.$refs['main-form'].validate((valid) => bool = valid);
      return bool;
    },

    async submit() {
      if (!this.verifyForm()) return false;
      this.mainQuery.url = this.mainQuery.urllist[0].url;

      console.log(this.mainQuery)
      delete this.mainQuery.urllist
      this.loading = true;
      if (this.data) {
        await this.submitSet();
      }
      else {
        await this.submitAdd();
      }

      this.loading = false;

    },

    async submitAdd() {

      try {
        await ApiMain.add(this.mainQuery);
        this.$message({ message: '添加成功', type: 'success' });
        this.close();
      } catch (err) {
      }

    },

    async submitSet() {
      this.mainQuery.id = this.data.id;
      try {
        await ApiMain.set(this.mainQuery);
        this.$message({ message: '修改成功', type: 'success' });
        this.close();
      } catch (e) {
      }

    },

    async submitDel() {
      this.popDeleteVisible = false;
      this.loading = true;

      try {
        await ApiMain.del({ id: this.id })
        this.$message({ message: '删除成功', type: 'success' });
        this.close();
      } catch (e) {
      }

      this.loading = false;

    },
  }
}
</script>

<style>
</style>
